package com.hex.tcpproxy.process;

import com.hex.tcpproxy.util.ProxyClient;
import com.hex.tcpproxy.util.ProxyHandler;
import com.hex.tcpproxy.util.ProxyServer;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: [wujie]
 * @createTime: [2019/10/9 8:38]
 * @description:
 */
public class MainClient implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(MainClient.class);
    private Integer port;
    private ProxyHandler proxyHandler;
    private String host;
    private Map<String, FakeClient> map = new ConcurrentHashMap<>();

    public MainClient(String address) {
        String[] split = address.split(":");
        this.host = split[0];
        this.port = Integer.parseInt(split[1]);
    }

    @Override
    public void run() {
        proxyHandler = new ProxyHandler() {
            @Override
            public void read(String address, byte[] bytes) {
                processData(bytes);
            }

            @Override
            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                tryRegister(ctx);
                feedBack("connect".getBytes());
            }
        };
        ProxyClient client = new ProxyClient(host, port, proxyHandler);
        client.connect();
    }

    private void processData(byte[] bytes) {
        DataExplain dataExplain = new DataExplain(bytes);
        //open
        if ("O".equals(dataExplain.getCmd())) {
            String address = DataExplain.getAddressString(dataExplain.getPara());
            logger.info("创建连接为{}的client", address);
            FakeClient fakeClient = new FakeClient(address, this);
            Thread thread = new Thread(fakeClient);
            thread.start();
            map.put(address, fakeClient);
        }
        //close
        else if ("C".equals(dataExplain.getCmd())) {
            String address = DataExplain.getAddressString(dataExplain.getPara());
            logger.info("关闭连接为{}client", address);
            map.remove(address).close();
        }
        //send
        else if ("S".equals(dataExplain.getCmd())) {
            //logger.info("给连接为{}的client发送消息", DataExplain.getAddressString(dataExplain.getPara()));
        }
    }

    public void feedBack(byte[] bytes) {
        DataExplain dataExplain = new DataExplain("F", bytes, null);
        proxyHandler.writeAll(dataExplain.getData());
    }

    public void writeBack(String address, byte[] bytes) {
        DataExplain dataExplain = new DataExplain("W", DataExplain.getAddressBytes(address), bytes);
        proxyHandler.writeAll(dataExplain.getData());
    }


}
